package org.dawfinn.droiditarian.deedlocationupload;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;

import org.dawfinn.droiditarian.data.Deed;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.location.Location;
import android.util.Log;

public class InternetDeedLocationUpload implements DeedLocationUpload {

	private final String path;
	private static final String REQUEST_METHOD = "POST";

	public InternetDeedLocationUpload(String path) {
		this.path = path;
	}

	public void sendLocation(Location location, Deed deed, Bitmap bitmap) {
		URL url;
		try {
			url = new URL(path + "?name=" + URLEncoder.encode(deed.getName(), "UTF-8") + "&lat=" + URLEncoder.encode("" + location.getLatitude())
			        + "&lng=" + URLEncoder.encode("" + location.getLongitude()));

			HttpURLConnection c = (HttpURLConnection) url.openConnection();
			c.setDoInput(true);
			c.setRequestMethod(REQUEST_METHOD);
			c.setDoOutput(true);
			c.connect();
			OutputStream output = c.getOutputStream();

			if (bitmap != null) {
				Log.i("InternetDeedLocationUpload", "Trying to upload image...");
				bitmap.compress(CompressFormat.JPEG, 50, output);
				Log.i("InternetDeedLocationUpload", "Finished uploading image...");
			} else {
				Log.i("InternetDeedLocationUpload", "Uploading without image");
			}
			
			output.close();

			Scanner result = new Scanner(c.getInputStream());
			// check for success
			result.close();

		} catch (IOException e) {
			Log.e("InternetDeedLocationUpload", "Failure uploading location", e);
		}
	}
}
